<template>
  <div style="width: 100%">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="resourceStore.uploadUrl"
      name="formFiles"
      :limit="5"
      :auto-upload="false"
      :on-success="handleUploadSuccess"
      :headers="uploadHeaders"
      :show-file-list="false"
      :on-change="fileChange"
      :file-list="fileList"
      :on-error="handleUploadError"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <template #tip>
        <div class="el-upload__tip text-red">仅支持一个文件，小于1M</div>
      </template>
      &nbsp;
      <el-button class="ml-3" type="test" @click="uploadFile"> 上传 </el-button>
    </el-upload>

    <div v-for="item in fileList" :key="item.uid">
      <span>{{ item.name }}</span>
      &nbsp;
      <el-button type="text" @click="removeFile(item.uid)">
        <el-icon><Close /></el-icon>
      </el-button>
      <el-progress
        :percentage="getProgressPercentage(item)"
        :status="getProgressStatus(item)"
        >{{ item.status }}</el-progress
      >
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, nextTick } from "vue";
import { useResourceStore } from "@/stores/resource";
import { useAppUserStore } from "@/stores/appUser";
import { ElMessage } from "element-plus";

const emit = defineEmits(["file-update"]);

const appUserStore = useAppUserStore();
const resourceStore = useResourceStore();
const fileList = ref([]);

const uploadRef = ref(null);
const uploadHeaders = computed(() => {
  return {
    Authorization: "Bearer " + appUserStore.token,
  };
});

const getProgressPercentage = (item) => {
  return item.status == "uploading" && item.percentage > 90
    ? 90
    : item.percentage;
};
const getProgressStatus = (item) => {
  return item.status == "ready"
    ? "warning"
    : item.status == "uploading"
    ? ""
    : "success";
};

const uploadFile = async () => {
  uploadRef.value.submit();
};

const removeFile = (uid) => {
  fileList.value = fileList.value.filter((item) => item.uid != uid);
};

const handleUploadError = (err) => {
  try {
    const errObj = JSON.parse(err.message);
    if (errObj && errObj.msg) {
        ElMessage({
          message: errObj.msg,
          type: "error",
          duration: 3 * 1000,
        });
    }
  } catch (e) {}
};

const fileChange = (file, files) => {
  fileList.value = files;
  console.log("files", JSON.parse(JSON.stringify(files)));
};
const handleUploadSuccess = (res) => {
  const fileIds = fileList.value.map((item) => {
    return item.response && item.response.data && item.response.data.id;
  });
  if (fileIds.length == 0) return;
  emit("file-uploaded", fileIds, fileList.value);
};
</script>

<style lang="less" scoped></style>
